use yew::prelude::*;
use yew_router::prelude::*;

use crate::{
  components::{crate_form::CrateForm, header::Header},
  contexts::CurrentUserContext,
  hooks::use_rustaceans,
  pages::slidebar::Slidebar,
  Route,
};

#[function_component]
pub fn CratesAdd() -> Html {
  let current_user_ctx = use_context::<CurrentUserContext>()
    .expect("Current user context is missing");

  match &current_user_ctx.token {
    Some(token) => {
      let loading = html! { <p>{"loading..."}</p> };

      html! {
        <>
          <Header/>
          <Slidebar/>
          <div>
            <Suspense fallback={loading}>
              <CrateAddForm token={token.clone()}/>
            </Suspense>
          </div>
        </>
      }
    }
    None => html! {
      <Redirect<Route> to={Route::Login}/>
    },
  }
}

#[derive(Properties, PartialEq)]
struct CrateAddFormProps {
  pub token: AttrValue,
}

#[function_component]
fn CrateAddForm(props: &CrateAddFormProps) -> HtmlResult {
  let rustanceans = use_rustaceans(&props.token.as_str())?;

  Ok(html! {
    <CrateForm authors={rustanceans}/>
  })
}
